Sometimes we have to evaluate more than just a few cases, making ElseIf a tad cumbersome (do YOU want to write 20 ElseIf’s? I don’t!)
Enter the more streamlined and efficient SWITCH command.
Let’s add some more trucks to our list, shall we?
<?php
$truck = "Chevy";
echo "Drive a $truck, <br/>";
switch ($truck){
case "Dodge":
echo "Ram Tough!";
break;
case "Ford":
echo "Built Ford Tough!";
break;
case "Toyota":
echo "Got The Guts?";
break;
case "Nissan":
echo "Shift_power";
break;
case "GMC":
echo "Professional Grade";
break;
} ?>
That looks a little cleaner, don’t you think?
A tad less clumsy that an equal number of If/Else statements.
Make sure when you use Switch to include the “break” statement - it not, the information will be processed until the script “breaks” or ends.
Also, notice that there is no default statement for when we match our condition! We need to add something to Switch - the default case.
<?php
$truck = "Chevy";
echo "Drive a $truck, <br/>";
switch ($truck){
case "Dodge":
echo "Ram Tough!";
break;
case "Ford":
echo "Built Ford Tough!";
break;
case "Toyota":
echo "Got The Guts?";
break;
case "Nissan":
echo "Shift_power";
break;
case "GMC":
echo "Professional Grade";
break;
default:
echo "We’ll Be There!";
break;
} ?>
This way, if there are no matching cases, our default is displayed.
0 Comments
|
David Rentson
If this free PHP and MYSQL Tutorial is helpful for you... Great! Archives
October 2008
Categories
All
|